package com.tanglongan.concurrent.thread;

import java.util.concurrent.locks.LockSupport;

public class InterruptDemo {

    public static final int SLEEP_GAP = 5000;   //睡眠时长

    private static void sleepSeconds(int l) {
        LockSupport.parkNanos(l * 1000L * 1000L * 1000L);
    }

    static class SleepDemoThread extends Thread {
        static int threadSeqNumber = 1;

        public SleepDemoThread() {
            super("sleepThread " + (threadSeqNumber++));
        }

        @Override
        public void run() {
            System.out.println(getName() + "=====>进入睡眠");

            try {
                Thread.sleep(SLEEP_GAP);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(getName() + " 发生被异常中断");
                return;
            }
            System.out.println(getName() + "- 运行结束. ");
        }
    }


    public static void main(String[] args) {
        Thread sThread1 = new SleepDemoThread();
        sThread1.start();
        Thread sThread2 = new SleepDemoThread();
        sThread2.start();

        sleepSeconds(2);        //主线程等待2秒
        sThread1.interrupt();   //打断线程1

        sleepSeconds(5);        //主线程等待5秒
        sThread2.interrupt();   //打断线程2，此时线程2已经终止

        sleepSeconds(1);        //主线程等待1秒
        System.out.println("程序运行结束");
    }
}
